using Digitalmes.Domain.Entities.Mes.Equipments;
using Digitalmes.Domain.Entities.Mes.Masters;

namespace Digitalmes.Application.Mes.Equipments.Machinery.Commands;

/// <summary>
/// 设备更新命令。
/// </summary>
public sealed record UpdateMachineryCommand(long Id, EquipMachineryDto Machinery) : IRequest<IResult<bool>>;

internal sealed class UpdateMachineryCommandHandler(IRepository<EquipMachinery> repo, IRepository<MdWorkstation> workstationRepo)
    : IRequestHandler<UpdateMachineryCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateMachineryCommand request, CancellationToken cancellationToken)
    {
        // 检查编号是否已存在。
        if (await repo.IsAnyAsync(m => m.MachineryCode == request.Machinery.MachineryCode && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("设备编号已存在");
        }

        var machinery = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (machinery == null)
        {
            return Result.Failure("未找到要更新的设备");
        }

        // 设置产线 Id
        if (machinery.WorkstationId != request.Machinery.WorkstationId)
        {
            var workstation = await workstationRepo.GetByIdAsync(request.Machinery.WorkstationId, cancellationToken);
            if (workstation == null)
            {
                return Result.Failure("指定的工位不存在");
            }

            machinery.LineId = workstation.LineId;
        }

        machinery.MachineryName = request.Machinery.MachineryName;
        machinery.Brand = request.Machinery.Brand;
        machinery.Model = request.Machinery.Model;
        machinery.Spec = request.Machinery.Spec;
        machinery.Manufacturer = request.Machinery.Manufacturer;
        machinery.PurchaseDate = request.Machinery.PurchaseDate;
        machinery.WorkstationId = request.Machinery.WorkstationId;
        machinery.Alias = request.Machinery.Alias;
        machinery.Remark = request.Machinery.Remark;
        machinery.Status = request.Machinery.Status;

        var ok = await repo.UpdateAsync(machinery, m => new
        {
            m.MachineryName,
            m.Brand,
            m.Model,
            m.Spec,
            m.Manufacturer,
            m.PurchaseDate,
            m.LineId,
            m.WorkstationId,
            m.Alias,
            m.Remark,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
